//
//  QYXDailyViewController.m
//  OpenYourEyes
//
//  Created by dllo on 16/6/6.
//  Copyright © 2016年 Google AdWords. All rights reserved.
//

#import "QYXDailyViewController.h"
#define kDailyNet [NSString stringWithFormat:@"http://baobab.wandoujia.com/api/v2/feed?_date=%ld&f=iphone&net=wifi&num=7&u=aafd829df8ff2d571a778ed3cca27eb68b16bd7d&v=2.2.0&vc=721", 1465374346624]

//1465264035944
#import "QYXDailyModel.h"
#import "QYXDailyTableViewCell.h"
#import "QYXDailyItemListModel.h"
#import "QYXDailyDetailViewController.h"
#import "AppDelegate.h"
#import "MagicMoveTransition.h"

@interface QYXDailyViewController ()<UITableViewDelegate, UITableViewDataSource, PopIndexDelegate, UINavigationControllerDelegate>

/** 界面数据源 */
@property (nonatomic, strong) NSMutableArray *dataSource;

/** 头视图 */
@property (nonatomic, strong) UIView *headerView;
/** 存放网址的属性 */
@property (nonatomic, copy) NSString *webString;

/** 装section的数据源 */
@property (nonatomic, strong) NSMutableArray *sectionDataSource;

@end

@implementation QYXDailyViewController
- (void)dealloc
{
    _mainTableView.delegate = nil;
    _mainTableView.dataSource = nil;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    //建页面:
    [self createTableView];
    //请求数据:
    [self createDataSource];
    
    
}


#pragma mark -- 初始化tableView
- (void)createTableView
{
    self.dataSource = [NSMutableArray array];
    self.sectionDataSource = [NSMutableArray array];
    
    //tableView初始化
    self.view.backgroundColor = [UIColor whiteColor];
    self.mainTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight) style:UITableViewStyleGrouped];
    self.headerView = [[UIView alloc] initWithFrame:CGRectMake(0, -20, kScreenWidth, 64)];
    self.headerView.backgroundColor = [UIColor clearColor];
//    self.mainTableView.tableHeaderView = _headerView;
    self.mainTableView.delegate = self;
    self.mainTableView.dataSource = self;
    self.mainTableView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:_mainTableView];
    //注册cell
    [self.mainTableView registerClass:[QYXDailyTableViewCell class] forCellReuseIdentifier:@"dailyCell"];
    
    /** 上拉加载下拉刷新 */
    self.mainTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self getData];
    }];
    self.mainTableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        [self getModeData];
    }];
}
#pragma mark -- 解析数据:
- (void)createDataSource
{
    [QYXNetTool getNetWithUrl:kDailyNet urlBody:nil header:nil response:QYXJSON success:^(id result) {
        if (result) {
            self.webString = [result objectForKey:@"nextPageUrl"];
            for (NSDictionary *dic in [result objectForKey:@"issueList"]) {
                QYXDailyModel *model = [[QYXDailyModel alloc] initWithDic:dic];
                [self.dataSource addObject:model];
                
            /** section数据处理 */
                NSDictionary *dict = [[dic objectForKey:@"itemList"] objectAtIndex:0];
                [self.sectionDataSource addObject:dict];
            }
            
            if (self.dataSource.count != 0) {
                [self.mainTableView reloadData];
                [self.mainTableView.mj_header endRefreshing];
            }
        }
    } failure:^(NSError *error) {
        
    }];
}
- (void)createMoreDataSource
{
    if (![self.webString isEqualToString:@""]) {
        NSLog(@"%@", self.webString);
        [QYXNetTool getNetWithUrl:_webString urlBody:nil header:nil response:QYXJSON success:^(id result) {
            if (result) {
                self.webString = [result objectForKey:@"nextPageUrl"];
                for (NSDictionary *dic in [result objectForKey:@"issueList"]) {
                    QYXDailyModel *model = [[QYXDailyModel alloc] initWithDic:dic];
                    [self.dataSource addObject:model];
                    
                    
                    /** section数据处理 */
                    NSDictionary *dict = [[dic objectForKey:@"itemList"] objectAtIndex:0];
                    [self.sectionDataSource addObject:dict];
                }
                if (self.dataSource.count != 0) {
                    [self.mainTableView reloadData];
                    [self.mainTableView.mj_footer endRefreshing];
                }
            }
        } failure:^(NSError *error) {
            
        }];
    }
}
#pragma mark -- 上拉加载,下拉刷新:
- (void)getData
{
    [self.dataSource removeAllObjects];
    [self.sectionDataSource removeAllObjects];
    [self.mainTableView reloadData];
    [self createDataSource];
}
- (void)getModeData
{
    [self createMoreDataSource];
}
#pragma mark -- tableView协议方法:
/** section数量 */
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.sectionDataSource.count;
}
/** cell数量 */
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    QYXDailyModel *model = [self.dataSource objectAtIndex:section];
    return model.itemList.count;
}
/** section自定义 */
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return nil;
    }
    UIView *sectionView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 50)];
    sectionView.backgroundColor = [UIColor whiteColor];
    
    if ([[[self.sectionDataSource objectAtIndex:section] objectForKey:@"type"] isEqualToString:@"imageHeader"]) {
        UIImageView *mainImageView = [[UIImageView alloc] initWithFrame:CGRectMake(kScreenWidth / 4 + 25, 15, kScreenWidth / 4 + kScreenWidth / 4 / 2, 30)];
        NSString *string = [[[self.sectionDataSource objectAtIndex:section] objectForKey:@"data"] objectForKey:@"image"];
        [mainImageView sd_setImageWithURL:[NSURL URLWithString:string] placeholderImage:kPlaceHolderImage];
        [sectionView addSubview:mainImageView];
    }
    if ([[[self.sectionDataSource objectAtIndex:section] objectForKey:@"type"] isEqualToString:@"textHeader"]) {
        UILabel *label = [[UILabel alloc] initWithFrame:sectionView.bounds];
        label.textAlignment = 1;
        label.font = [UIFont fontWithName:@"Lobster 1.4" size:17];
        NSString *string = [[[self.sectionDataSource objectAtIndex:section] objectForKey:@"data"] objectForKey:@"text"];
        label.text = string;
        [sectionView addSubview:label];
    }
    return sectionView;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.1;
}
/** section高度 */
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return 0.1;
    }
    return 50;
}
/** cell高度 */
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 240 * KFitHeight;
}
/** cell */
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    QYXDailyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"dailyCell"];
    QYXDailyModel *model = [self.dataSource objectAtIndex:indexPath.section];
    cell.model = [model.itemList objectAtIndex:indexPath.row];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}
/** 点击方法 */
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    QYXDailyDetailViewController *detailVC = [QYXDailyDetailViewController new];
    detailVC.delegate = self;
    QYXDailyModel *model = [self.dataSource objectAtIndex:indexPath.section];
    detailVC.listDataSource = model.itemList;
//    detailVC.modelSection = indexPath.section;
    detailVC.modelRow = indexPath.row;
    AppDelegate *tempDelegate = [UIApplication sharedApplication].delegate;
    tempDelegate.tabBar.backView.hidden = YES;
    
    [self.navigationController pushViewController:detailVC animated:YES];

}



- (void)popIndexModel:(QYXDailyItemListModel *)model sect:(NSInteger)section
{
//    QYXDailyModel *datamodel = [self.dataSource objectAtIndex:section];
//    NSInteger row = [datamodel.itemList indexOfObject:model];
//    [self.mainTableView setContentOffset:CGPointMake(0, kScreenHeight / 3 * row)];
    
}


- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    // 这是的转场动画属于自定义push 由导航栏来控制
    // 属于导航控制器来负责转场
    // 我们让当前控制器来作为 UINavigationControllerDelegate代理对象， 并实现协议方法。
    
    self.navigationController.delegate = self;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    AppDelegate *tempDelegate = [UIApplication sharedApplication].delegate;
    tempDelegate.tabBar.backView.hidden = NO;
}


#pragma mark - 返回我们写好的转场对象


- (nullable id <UIViewControllerAnimatedTransitioning>)navigationController:(UINavigationController *)navigationController
                                            animationControllerForOperation:(UINavigationControllerOperation)operation
                                                         fromViewController:(UIViewController *)fromVC
                                                           toViewController:(UIViewController *)toVC
{
    if ([toVC isKindOfClass:[QYXDailyDetailViewController class]]) {
        MagicMoveTransition *transition = [[MagicMoveTransition alloc] init];
        return transition;
    }
    return nil;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
